import MapboxDraw from "@mapbox/mapbox-gl-draw";

import { AttackArrow, toLineGeojson } from "./generate";

const doubleClickZoom = MapboxDraw.lib.doubleClickZoom;

function isEventAtCoordinates(coordinates, lngLat) {
	if (!lngLat) return false;

	const { lng, lat } = lngLat;
	for (let i = 0; i < coordinates.length; i++) {
		const coord = coordinates[i];
		if (coord[0] === lng && coord[1] === lat) {
			return true;
		}
	}
	return false;
}

export const DrawAttackArrow = {
	onSetup: function (opts) {
		const clickCount = 0;

		doubleClickZoom.disable(this);

		return {
			coordinates: [],
			clickCount,
		};
	},
	onClick: function (state, e) {
		const { lngLat } = e;
		const { coordinates, clickCount } = state;

		if (
			isEventAtCoordinates(coordinates, lngLat) &&
			clickCount === coordinates.length
		) {
			this.map.fire("draw.create", {
				mode: "attack_arrow",
				id: state.feature.id,
				features: [state.feature.toGeoJSON()],
				controlPnts: state.coordinates,
			});

			this.changeMode("simple_select", {}, { silent: true });
			return;
		}

		coordinates[clickCount] = [lngLat.lng, lngLat.lat];
		state.clickCount += 1;
	},

	onMouseMove: function (state, e) {
		// console.log("onmousemove--state", state);
		const { clickCount, coordinates } = state;

		if (clickCount > 1) {
			coordinates[clickCount] = [e.lngLat.lng, e.lngLat.lat];
		}

		this.updateFeature(state);
	},

	onStop: function (state) {
		doubleClickZoom.enable(this);

		state.coordinates = [];
		state.clickCount = 0;
	},

	toDisplayFeatures: (state, geojson, display) => {
		display(geojson);
	},

	updateFeature: function (state) {
		const { coordinates, feature } = state;
		if (coordinates.length < 3) return;

		const coords = AttackArrow.generate(coordinates);
		const arrowFeat = toLineGeojson(coords);

		if (feature) {
			feature.setCoordinates(arrowFeat.geometry.coordinates);
		} else {
			const feat = this.newFeature(arrowFeat);
			this.addFeature(feat);

			state.feature = feat;
		}
	},
};
